package com.awise.app.home.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.awise.R;
import com.awise.app.cloudy.activity.CloudyActivity;
import com.awise.app.home.adapter.ItemAdapter;
import com.awise.app.lighting.activity.LightingActivity;
import com.awise.app.manual.activity.ManualActivity;
import com.awise.app.more.activity.MoreActivity;
import com.awise.app.sunrise.activity.SunriseActivity;
import com.awise.app.timer.activity.TimerActivity;
import com.awise.base.BaseActivity;
import com.awise.http.RoverGlobal;
import com.awise.http.RoverInterface;
import com.awise.http.RoverInterfaceUser;
import com.awise.util.Constant;
import com.awise.util.TakePhotoUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;


public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener, View
        .OnClickListener {
    private ArrayList<Map<String, Object>> data_list;
    private ItemAdapter sim_adapter;
    private GridView gview;
    private TextView s_back;
    private ImageView iv_switches, iv_camera, iv_background;
    private RelativeLayout rl_layout;

    private LocalBroadcastManager mLocalBroadcastManager;
    private boolean isFirst = true;
    private int TEMPERATURE_VISIBLE = 0;
    private int TEMPERATURE_GONE = 1;
    private int TEMPERATURE_STATUS = 0;
    AnimationSet animationSet;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_main);
        showLoadingView();
        initSocket(); //初始化网络连接
        initView();
    }


    public void initView() {
        String[] iconName = {getResources().getString(R.string.manual), getResources().getString
                (R.string.cloudy), getResources().getString(R.string.lighting),
                getResources().getString(R.string.sunrise), getResources().getString(R.string
                .timer), getResources().getString(R.string.more)};
        int[] icon = {R.mipmap.hand_1, R.mipmap.cloudy_1, R.mipmap.light_1, R.mipmap.sunrise_1, R
                .mipmap.timer_1, R.mipmap.setting_1};
        gview = (GridView) this.findViewById(R.id.gv_name_pic);
        data_list = new ArrayList<Map<String, Object>>();
        getData();
        String[] from = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        //        sim_adapter = new SimpleAdapter(this, data_list, R.layout.home_item, from, to);
        sim_adapter = new ItemAdapter(this, data_list);
        gview.setAdapter(sim_adapter);   //配置适配器
        gview.setOnItemClickListener(this);
        s_back = (TextView) this.findViewById(R.id.tv_back);
        TextView textView_content = (TextView) this.findViewById(R.id.textView_content);
        textView_content.setText(R.string.app_name);
        s_back.setVisibility(View.INVISIBLE);
        iv_switches = (ImageView) this.findViewById(R.id.iv_switches);
        iv_switches.setOnClickListener(this);
        iv_camera = (ImageView) this.findViewById(R.id.iv_camera);
        iv_camera.setOnClickListener(this);
        rl_layout = (RelativeLayout) this.findViewById(R.id.rl_layout);
        iv_background = (ImageView) this.findViewById(R.id.iv_background);
        String imagePath = getSP(this, "photoUri", "");
        if (!TextUtils.isEmpty(imagePath)) {
            try {
                iv_background.setImageURI(Uri.parse(imagePath));
            } catch (Exception e) {
                iv_background.setBackgroundResource(R.mipmap.background);
                e.printStackTrace();
            }
        }

        LinearLayout home_main_icon_layout_1 = (LinearLayout) this.findViewById(R.id
                .home_main_icon_layout_1);
        ((ImageView) home_main_icon_layout_1.findViewById(R.id.image_main_pic)).setImageDrawable
                (getResources().getDrawable(icon[0]));
        ((TextView) home_main_icon_layout_1.findViewById(R.id.tv_title)).setText(iconName[0]);
        image_scale1 = (ImageView) home_main_icon_layout_1.findViewById(R.id.image_scale);

        LinearLayout home_main_icon_layout_2 = (LinearLayout) this.findViewById(R.id
                .home_main_icon_layout_2);
        ((ImageView) home_main_icon_layout_2.findViewById(R.id.image_main_pic)).setImageDrawable
                (getResources().getDrawable(icon[1]));
        ((TextView) home_main_icon_layout_2.findViewById(R.id.tv_title)).setText(iconName[1]);
        image_scale2 = (ImageView) home_main_icon_layout_2.findViewById(R.id.image_scale);

        LinearLayout home_main_icon_layout_3 = (LinearLayout) this.findViewById(R.id
                .home_main_icon_layout_3);
        ((ImageView) home_main_icon_layout_3.findViewById(R.id.image_main_pic)).setImageDrawable
                (getResources().getDrawable(icon[2]));
        ((TextView) home_main_icon_layout_3.findViewById(R.id.tv_title)).setText(iconName[2]);
        image_scale3 = (ImageView) home_main_icon_layout_3.findViewById(R.id.image_scale);

        LinearLayout home_main_icon_layout_4 = (LinearLayout) this.findViewById(R.id
                .home_main_icon_layout_4);
        ((ImageView) home_main_icon_layout_4.findViewById(R.id.image_main_pic)).setImageDrawable
                (getResources().getDrawable(icon[3]));
        ((TextView) home_main_icon_layout_4.findViewById(R.id.tv_title)).setText(iconName[3]);
        image_scale4 = (ImageView) home_main_icon_layout_4.findViewById(R.id.image_scale);

        LinearLayout home_main_icon_layout_5 = (LinearLayout) this.findViewById(R.id
                .home_main_icon_layout_5);
        ((ImageView) home_main_icon_layout_5.findViewById(R.id.image_main_pic)).setImageDrawable
                (getResources().getDrawable(icon[4]));
        ((TextView) home_main_icon_layout_5.findViewById(R.id.tv_title)).setText(iconName[4]);
        image_scale5 = (ImageView) home_main_icon_layout_5.findViewById(R.id.image_scale);

        LinearLayout home_main_icon_layout_6 = (LinearLayout) this.findViewById(R.id
                .home_main_icon_layout_6);
        ((ImageView) home_main_icon_layout_6.findViewById(R.id.image_main_pic)).setImageDrawable
                (getResources().getDrawable(icon[5]));
        ((TextView) home_main_icon_layout_6.findViewById(R.id.tv_title)).setText(iconName[5]);
        image_scale6 = (ImageView) home_main_icon_layout_6.findViewById(R.id.image_scale);
        home_main_icon_layout_1.setOnClickListener(this);
        home_main_icon_layout_2.setOnClickListener(this);
        home_main_icon_layout_3.setOnClickListener(this);
        home_main_icon_layout_4.setOnClickListener(this);
        home_main_icon_layout_5.setOnClickListener(this);
        home_main_icon_layout_6.setOnClickListener(this);
        animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(500);//0.5秒完成动画
        //将AlphaAnimation这个已经设置好的动画添加到 AnimationSet中
        scaleAnimation.setRepeatCount(Integer.MAX_VALUE);//动画的重复次数
        animationSet.addAnimation(scaleAnimation);
    }

    ImageView image_scale1, image_scale2, image_scale3, image_scale4, image_scale5, image_scale6;

    public List<Map<String, Object>> getData() {
        String[] iconName = {getResources().getString(R.string.manual), getResources().getString
                (R.string.cloudy), getResources().getString(R.string.lighting),
                getResources().getString(R.string.sunrise), getResources().getString(R.string
                .timer), getResources().getString(R.string.more)};
        int[] icon = {R.mipmap.hand_1, R.mipmap.cloudy_1, R.mipmap.light_1, R.mipmap.sunrise_1, R
                .mipmap.timer_1, R.mipmap.setting_1};
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            data_list.add(map);
        }
        return data_list;
    }

    // 初始化网络连接
    public void initSocket() {
        RoverGlobal.getInstance().interfaceUser = new RoverInterfaceUser();
        RoverGlobal.getInstance().interfaceUser.setRoverInterface(new RoverInterface() {
            @Override
            public void connectHostSuccess() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendSystemTime();
                    }
                }, 200);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingView();
                        Toast.makeText(MainActivity.this, R.string.connect_successful, Toast
                                .LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void connectHostFailed() {
                if (isFirst) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoadingView();
                            Toast.makeText(MainActivity.this, R.string.no_connect, Toast
                                    .LENGTH_SHORT).show();
                        }
                    });
                    isFirst = false;
                }
            }

            @Override
            public void receivedDataFromHost(byte[] buffer) {
                if (buffer != null) {
                    //                    System.out.println("buffer:"+buffer);
                    byte comman1 = buffer[4];
                    byte comman2 = buffer[5];
                    switch (comman1) {
                        case 0x00: //恢复出厂设置返回数据
                            sendDataByBroadcast(Constant.MORE_ACTION, buffer);
                            break;
                        case 0x01: //返回的设备类型和MAC地址

                            break;
                        case 0x0F: //下载定时器数据至控制器的回调状态
                            sendDataByBroadcast(Constant.TIMER_ACTION, buffer);
                            break;
                        case 0x13: //发送相关开关指令返回的数据
                            switch (comman2) {
                                case 0x1c: //定时器
                                    sendDataByBroadcast(Constant.TIMER_ACTION, buffer);
                                    break;
                                case 0x31: //闪电
                                    break;
                                case 0x32:  //云彩
                                    break;
                                case 0x35:  //日出日落
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 0x14: //发送总开关指令返回的数据
                            break;
                        case 0x17: //发送 云彩 指令返回的数据
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, R.string
                                            .setting_successful, Toast.LENGTH_SHORT).show();
                                }
                            });
                            break;
                        case 0x18: //发送 闪电 指令返回的数据
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, R.string
                                            .setting_successful, Toast.LENGTH_SHORT).show();
                                }
                            });

                            break;
                        case 0x1A: //读取数据
                            switch (comman2) {
                                case 0x13:  //获取总开关状态和正在运行的模式
                                    byte value1 = buffer[8];//开关
                                    final byte value2 = buffer[9];//模式
                                    //                                    0x01(开)/0x00(关)
                                    flag = (value1 == 0x01 ? true : false);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            iv_switches.setImageResource(flag ? R.mipmap
                                                    .switch_image_open : R.mipmap
                                                    .switch_image_close);
                                        }
                                    });
                                    switch (value2) {//当前运行模式
                                        case 0x16: //手动模式
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    image_scale1.setVisibility(View.VISIBLE);
                                                    image_scale2.setVisibility(View.GONE);
                                                    image_scale3.setVisibility(View.GONE);
                                                    image_scale4.setVisibility(View.GONE);
                                                    image_scale5.setVisibility(View.GONE);
                                                    image_scale6.setVisibility(View.GONE);
//                                                  image_scale1.startAnimation(animationSet); //启动动画
                                                }
                                            });

                                            break;
                                        case 0x17: //云彩模式
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    image_scale1.setVisibility(View.GONE);
                                                    image_scale2.setVisibility(View.VISIBLE);
                                                    image_scale3.setVisibility(View.GONE);
                                                    image_scale4.setVisibility(View.GONE);
                                                    image_scale5.setVisibility(View.GONE);
                                                    image_scale6.setVisibility(View.GONE);
//                                                   image_scale2.startAnimation(animationSet); //启动动画
                                                }
                                            });
                                            break;
                                        case 0x18: //闪电模式
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    image_scale1.setVisibility(View.GONE);
                                                    image_scale2.setVisibility(View.GONE);
                                                    image_scale3.setVisibility(View.VISIBLE);
                                                    image_scale4.setVisibility(View.GONE);
                                                    image_scale5.setVisibility(View.GONE);
                                                    image_scale6.setVisibility(View.GONE);
//                                                  image_scale3.startAnimation(animationSet); //启动动画
                                                }
                                            });

                                            break;
                                        case 0x34:  //日出日落
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    image_scale1.setVisibility(View.GONE);
                                                    image_scale2.setVisibility(View.GONE);
                                                    image_scale3.setVisibility(View.GONE);
                                                    image_scale4.setVisibility(View.VISIBLE);
                                                    image_scale5.setVisibility(View.GONE);
                                                    image_scale6.setVisibility(View.GONE);
//                                                  image_scale4.startAnimation(animationSet); //启动动画
                                                }
                                            });

                                            break;
                                        case 0x0f:  //定时器模式
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    image_scale1.setVisibility(View.GONE);
                                                    image_scale2.setVisibility(View.GONE);
                                                    image_scale3.setVisibility(View.GONE);
                                                    image_scale4.setVisibility(View.GONE);
                                                    image_scale5.setVisibility(View.VISIBLE);
                                                    image_scale6.setVisibility(View.GONE);
//                                                  image_scale5.startAnimation(animationSet); //启动动画
                                                }
                                            });

                                            break;
                                        default:
                                            break;
                                    }
                                    break;
                                case 0x16:  //获取通道值
                                    sendDataByBroadcast(Constant.MANUAL_ACTION, buffer);
                                    break;
                                case 0x21:  //获取设备温度
                                    byte value = buffer[8];//温度
                                    if (value == 0xff || value == -1) {
                                        TEMPERATURE_STATUS = TEMPERATURE_GONE;
                                    } else {
                                        sendDataByBroadcast(Constant.TEMPERATURE_ACTION, buffer);
                                        TEMPERATURE_STATUS = TEMPERATURE_VISIBLE;
                                    }
                                    break;
                                case 0x38:  //获取闪电数据
                                    sendDataByBroadcast(Constant.LIGHTLING_ACTION, buffer);
                                    break;
                                case 0x39:  //获取云彩数据
                                    sendDataByBroadcast(Constant.CLOUDY_ACTION, buffer);
                                    break;
                                case 0x3a:  //读取日出日落数据
                                    sendDataByBroadcast(Constant.SUNRISE_ACTION, buffer);
                                    break;
                                case 0x3b:  //读取当前控制器名字
                                    //                                    System.out.println
                                    // ("名字buffer="+buffer);
                                    break;
                                case 0x1f:  //读取当前控制器时间
                                    sendDataByBroadcast(Constant.MORE_ACTION, buffer);
                                    break;
                                case 0x12:  //读取定时器数据
                                    sendDataByBroadcast(Constant.TIMER_ACTION, buffer);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 0x22: //发送 设置风扇起转温度 指令返回的数据
                            break;
                        case 0x23: //发送 修改名字 指令返回的数据
                            break;
                        case 0x33: //发送 停止 多云、闪电、日出日落指令返回数据
                            break;
                        case 0x34: //发送 日出日落数据 指令返回的数据
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, R.string.success, Toast
                                            .LENGTH_SHORT).show();
                                }
                            });
                            break;
                        case 0x3d: //发送 开关客人模式 指令返回的数据
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        RoverGlobal.getInstance().initSocket();
        RoverGlobal.getInstance().setOnSocketListener(new RoverGlobal.onSocketListener() {
            @Override
            public void disconnect() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        s_back.setVisibility(View.INVISIBLE);
                    }
                });

            }

            @Override
            public void connected() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Drawable dra=  getResources().getDrawable(R.mipmap.break_pic);
                        dra.setBounds( 0, 0, dra.getMinimumWidth(),dra.getMinimumHeight());
                        s_back.setCompoundDrawables(dra,null,null,null);
                        s_back.setVisibility(View.VISIBLE);
                    }
                });
            }
        });

    }


    /**
     * 通过广播来发送数据
     *
     * @param action 发送广播的相应Action
     */
    private void sendDataByBroadcast(final String action, final byte[] data) {
        if (mLocalBroadcastManager == null) {
            mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(action);
                Bundle bundle = new Bundle();
                bundle.putByteArray("socket_data", data);
                intent.putExtras(bundle);
                mLocalBroadcastManager.sendBroadcast(intent);
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (i) {
            case 0:
                Intent manualIntent = new Intent(MainActivity.this, ManualActivity.class);
                //                manualIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(manualIntent);
                break;
            case 1:
                Intent cloudyIntent = new Intent(MainActivity.this, CloudyActivity.class);
                //                cloudyIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(cloudyIntent);
                break;
            case 2:
                Intent lightingIntent = new Intent(MainActivity.this, LightingActivity.class);
                //                lightingIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(lightingIntent);
                break;
            case 3:
                Intent sunriseIntent = new Intent(MainActivity.this, SunriseActivity.class);
                //                sunriseIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(sunriseIntent);
                break;
            case 4:
                Intent timerIntent = new Intent(MainActivity.this, TimerActivity.class);
                timerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(timerIntent);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_in_left);
                break;
            case 5:
                Intent moreIntent = new Intent(MainActivity.this, MoreActivity.class);
                moreIntent.putExtra("temperature", TEMPERATURE_STATUS);
                //                moreIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(moreIntent);
                break;
        }
    }

    protected void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dialog_main_content);
        builder.setTitle(R.string.dialog_title);
        builder.setPositiveButton(R.string.dialog_confirmation, new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(10);
            }
        });
        builder.setNegativeButton(R.string.dialog_cannel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog();
        }
        return false;
    }


    private boolean isConnect = false;
    private boolean flag = false;
    private Thread mThreadClient;
    private Uri imageUri;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home_main_icon_layout_1:
                Intent manualIntent = new Intent(MainActivity.this, ManualActivity.class);
                startActivity(manualIntent);
                break;
            case R.id.home_main_icon_layout_2:
                Intent cloudyIntent = new Intent(MainActivity.this, CloudyActivity.class);
                startActivity(cloudyIntent);
                break;
            case R.id.home_main_icon_layout_3:
                Intent lightingIntent = new Intent(MainActivity.this, LightingActivity.class);
                startActivity(lightingIntent);
                break;
            case R.id.home_main_icon_layout_4:
                Intent sunriseIntent = new Intent(MainActivity.this, SunriseActivity.class);
                startActivity(sunriseIntent);
                break;
            case R.id.home_main_icon_layout_5:
                Intent timerIntent = new Intent(MainActivity.this, TimerActivity.class);
                timerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(timerIntent);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_in_left);
                break;
            case R.id.home_main_icon_layout_6:
                Intent moreIntent = new Intent(MainActivity.this, MoreActivity.class);
                moreIntent.putExtra("temperature", TEMPERATURE_STATUS);
                startActivity(moreIntent);
                break;
            case R.id.iv_switches:
                if (flag) {
                    iv_switches.setImageResource(R.mipmap.switch_image_close);
                    //                    Toast.makeText(MainActivity.this, "关闭开关", Toast
                    // .LENGTH_SHORT).show();
                    flag = false;
                } else {
                    iv_switches.setImageResource(R.mipmap.switch_image_open);
                    //                    Toast.makeText(MainActivity.this, "打开开关", Toast
                    // .LENGTH_SHORT).show();
                    flag = true;
                }
                byte value;
                if (flag) {
                    value = 0x01;
                } else {
                    value = 0x00;
                }
                //                timerOpenOrClose(value);
                onOff(value);
                break;
            case R.id.iv_camera:

                showPopupWindow();
                break;
            case R.id.tv_main_popwindow_photo:
                try {
                    imageUri = TakePhotoUtils.takePhoto(this, 111);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mPopWindow.dismiss();
                break;
            case R.id.tv_main_popwindow_album:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 222);
                mPopWindow.dismiss();
                break;

            case R.id.tv_main_popwindow_cannel:
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            //            Toast.makeText(MainActivity.this, "点击取消从相册选择", Toast.LENGTH_LONG).show();
            return;
        } else if (requestCode == 222 && resultCode == RESULT_OK) {
            try {
                imageUri = data.getData();
                iv_background.setImageURI(imageUri);
                setSP(this, "photoUri", imageUri + "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 111 && resultCode == RESULT_OK) {
           /* Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath(), getOptions(imageUri
           .getPath()));
            iv_background.setImageBitmap(bitmap);*/
            iv_background.setImageURI(imageUri);
            setSP(this, "photoUri", imageUri + "");
        }
    }

    /**
     * 获取压缩图片的options
     *
     * @return
     */
    public static BitmapFactory.Options getOptions(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inSampleSize = 4;      //此项参数可以根据需求进行计算
        options.inJustDecodeBounds = false;

        return options;
    }

    TextView tv_main_popwindow_album, tv_main_popwindow_photo, tv_main_popwindow_cannel;
    private PopupWindow mPopWindow;

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout
                .main_photo_popwindow_layout, null);
        mPopWindow = new PopupWindow(contentView,
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams
                .WRAP_CONTENT, true);
        //设置各个控件的点击响应
        tv_main_popwindow_album = (TextView) contentView.findViewById(R.id.tv_main_popwindow_album);
        tv_main_popwindow_photo = (TextView) contentView.findViewById(R.id.tv_main_popwindow_photo);
        tv_main_popwindow_cannel = (TextView) contentView.findViewById(R.id
                .tv_main_popwindow_cannel);
        tv_main_popwindow_album.setOnClickListener(this);
        tv_main_popwindow_photo.setOnClickListener(this);
        tv_main_popwindow_cannel.setOnClickListener(this);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.home_main, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

    }

    public void onOff(byte value1) {
        //        System.out.println("value1:"+value1+"  "+value2+"  "+value3+"  "+value4+"
        // "+value5);
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x14, 0x00, 0x00, 0x01, value1, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    @Override
    protected void onStart() {
        super.onStart();
        readOnoffData();
        readTemperatureData();
    }

    public void readTemperatureData() {
        /* 读取温度值 c0 0a 11 01 1a 21 00 00 17*/
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x1a, 0x21, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    /* 设置设备名(Awise)
     C0 0A 11 01 23 00 00 05 41 77 69 73 65 FD*/
    public void readOnoffData() {
        //      读取总开关 主机	0xC0 0x0A	0x11	0x01	0x1A	0xxx	0x00 0x00
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x1a, 0x13, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    public void sendSystemTime() {
        //       发送时间 主机	0xC0 0x0A	0x11	0x01	0x20	0x00 0x07	年份(2字节)	月	日	小时
        // 		分	秒	星期		x
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x20, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        final Calendar c = Calendar.getInstance();
        TimeZone tz = TimeZone.getDefault();
        String TimeZoneData = tz.getDisplayName(false, TimeZone.SHORT);
        c.setTimeZone(TimeZone.getTimeZone(TimeZoneData));
        bytes[8] = (byte) (c.get(Calendar.YEAR) >> 8);
        bytes[9] = (byte) (c.get(Calendar.YEAR) % 256);
        bytes[10] = (byte) (c.get(Calendar.MONTH) + 1);
        bytes[11] = (byte) (c.get(Calendar.DAY_OF_MONTH));
        bytes[12] = (byte) (c.get(Calendar.HOUR_OF_DAY));
        bytes[13] = (byte) (c.get(Calendar.MINUTE));
        bytes[14] = (byte) (c.get(Calendar.SECOND));
        int week = c.get(Calendar.DAY_OF_WEEK);
        if (1 == week) {//星期天
            week = 7;
        } else if (2 == week) {//周一
            week = 1;
        } else if (3 == week) {//周二
            week = 2;
        } else if (4 == week) {//周三
            week = 3;
        } else if (5 == week) {//周四
            week = 4;
        } else if (6 == week) {//周五
            week = 5;
        } else if (7 == week) {//周六
            week = 6;
        }
        bytes[15] = (byte) (week);
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
        //   bb[0] = 0x07  bb[1]  =  0xe2     0x07e2  =  2018
 /*  Byte  bb[]=new Byte[2];
    int yearstr=2018;
    bb[0] =(byte)(yearstr>>8);
    bb[1]  = (byte)yearstr;
    System.out.println("yearstr=2018;bb[0]="+bb[0] +"  bb[1]="+bb[1]);
    System.out.println("时间："+c.get(Calendar.YEAR) + "年" + (c.get(Calendar.MONTH) + 1 )
                + "月" + c.get(Calendar.DAY_OF_MONTH)+"日"+"星期"+c.get(Calendar.DAY_OF_WEEK)+"/"
                +c.get(Calendar.HOUR_OF_DAY)+"小时"+c.get(Calendar.MINUTE)+"分钟"+c.get(Calendar.SECOND)+"秒");
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);*/
    }

}
